package com.example.demo_test.Controller;


import com.example.demo_test.Dao.GroupDao;
import com.example.demo_test.Dao.PersonDao;
import com.example.demo_test.Entity.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.function.ServerResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhanghong
 * @date 2021/6/10  0010 15:07
 */
@RestController
@RequestMapping("/up")
@CrossOrigin
public class FileUpload {
    @Autowired
    private PersonDao personDao;
    @Autowired
    private GroupDao groupDao;
    @Value( "${prop.upload-folder}" )
    private String uploadPath;
    @PostMapping("/uploadHead")
    public Result uploadHead(@RequestParam("file") MultipartFile file, @Param( "userId" )String userId,@Param( "groupId" )int groupId) throws FileNotFoundException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
//        System.out.println(file.getContentType());
        String token = request.getHeader("token");
        //获取文件在服务器的储存位置
//        String path = request.getRealPath("/uploadHead");
        String path = uploadPath;

        File filePath = new File(path);
        System.out.println("文件的保存路径：" + path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            System.out.println("目录不存在，创建目录:" + filePath);
            filePath.mkdir();
        }

        //获取原始文件名称(包含格式)
        String originalFileName = file.getOriginalFilename();
        System.out.println("原始文件名称：" + originalFileName);

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        System.out.println("文件类型：" + type);
        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        //设置文件新名称: 当前时间+文件名称（不包含格式）
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(d);
        String fileName = date + name + "." + type;
        System.out.println("新文件名称：" + fileName);

        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);

        //将文件保存到服务器指定位置
        try {
            file.transferTo(targetFile);
            System.out.println("上传成功");
            if(userId!=null) {
                personDao.updateAvatar( userId, fileName );
            }
            if(groupId!=0){
                groupDao.updateAvatar( groupId,fileName );
            }
            //将文件在服务器的存储路径返回
            return new Result(200,"上传成功",fileName);
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return new Result(400,"上传失败","");
        }


    }
    @GetMapping(value = "/getPhoto/{imgUrl}", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getPhoto(@PathVariable("imgUrl") String imgUrl) {
        try {
            File file = new File( uploadPath + imgUrl );
            FileInputStream inputStream = new FileInputStream( file );
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read( bytes, 0, inputStream.available() );
            return bytes;
        }catch (Exception e){
            return null;
        }
    }
}
